package com.javacv.plus.extensions.image.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.image.ImageProcessor;
import com.javacv.plus.extensions.image.ProcessorResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.global.opencv_imgcodecs;

import java.io.File;

/**
 * 保存图像步骤
 */
@Slf4j
public class SaveImageStep implements ProcessorStep<ImageProcessor, ProcessorResult> {

    @Override
    public ProcessorResult execute(ImageProcessor processor, ProcessorContext context) throws Exception {
        Mat currentImage = context.getAttribute("currentImage");
        if (currentImage == null) {
            throw new IllegalStateException("当前图像为空");
        }

        String outputPath = processor.getConfig().getOutputPath();
        if (outputPath == null || outputPath.trim().isEmpty()) {
            throw new IllegalArgumentException("输出路径不能为空");
        }

        // 确保输出目录存在
        File outputFile = new File(outputPath);
        File parentDir = outputFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }

        log.debug("保存图像到: {}", outputPath);

        // 使用 OpenCV 保存图像
        boolean success = opencv_imgcodecs.imwrite(outputPath, currentImage);
        
        if (!success) {
            throw new RuntimeException("保存图像失败: " + outputPath);
        }

        log.debug("图像保存成功");
        return null;
    }

    @Override
    public String getStepName() {
        return "SaveImage";
    }

    @Override
    public int getPriority() {
        return 999; // 最低优先级，确保最后执行
    }
} 